<?php

namespace App\GraphQL\Mutations\Order;

use App\Models\Order;
use GraphQL\Type\Definition\ResolveInfo;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
class WechatPay
{
    /**
     * Return a value for the field.
     *
     * @param  null  $rootValue Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param  mixed[]  $args The arguments that were passed into the field.
     * @param  \Nuwave\Lighthouse\Support\Contracts\GraphQLContext  $context Arbitrary data that is shared between all fields of a single query.
     * @param  \GraphQL\Type\Definition\ResolveInfo  $resolveInfo Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        
        $id = $args['id'];
        $order = $this->validate($id);
        $pay = \EasyWeChat::payment();
        $result = $pay->order->unify([
            'body' => '充电',
            'out_trade_no' => $order->id,
            'total_fee' => $order->paid_price,
            'notify_url' => 'https://ssyd.knowledgebird.cn/api/wechat/pay-notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => auth()->user()->open_id,
        ]);
        if($result['result_code']!=='SUCCESS'){
            throw new \Exception('系统错误!');
        }
        return [
            'time_stamp'=>time(),
            'nonce_str'=>$result['nonce_str'],
            'package'=>$result['prepay_id'],
            'pay_sign'=>$result['sign'],
            'sign_type'=>'MD5',
        ];
    }
    public function validate($id){
        $order = Order::find($id);
        if (!$order) {
            throw new \Exception('订单不存在!');
        }
        if($order->status !=='WAIT_PAY'){
            throw new \Exception('订单不能支付!');
        }
        if($order->paid_price <= 0){
            throw new \Exception('订单不能支付!');
        }
        return $order;
    }
}
